package com.tanhua.admin.service;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.mapper.AnalysisMapper;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.model.domain.Analysis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author SunSun
 * @date 2021/11/5
 */
@Service
public class AnalysisService {

    @Autowired
    private LogMapper logMapper;

    @Autowired
    private AnalysisMapper analysisMapper;

    public void analysis() throws ParseException {
        String today= new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String yesday= DateUtil.yesterday().toString("yyyy-MM-dd");
        //注册数量
        Integer regCount = logMapper.queryByTypeAndLogTime("0102", today);
        //登陆数量
        Integer loginCount = logMapper.queryByTypeAndLogTime("0101", today);
        //日活跃量
        Integer activeCount = logMapper.queryByLogTime(today);
        //次日留存
        Integer numRetention1d = logMapper.queryNumRetention1d(today, yesday);

        QueryWrapper<Analysis> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("record_date",new SimpleDateFormat("yyyy-MM-dd").parse(today));
        Analysis analysis = analysisMapper.selectOne(queryWrapper);
        if(analysis!=null){
            analysis.setNumLogin(loginCount);
            analysis.setNumActive(activeCount);
            analysis.setNumRegistered(regCount);
            analysis.setNumRetention1d(numRetention1d);
            analysis.setUpdated(new Date());
            analysisMapper.updateById(analysis);
        }else {
            analysis=new Analysis();
            analysis.setNumLogin(loginCount);
            analysis.setNumActive(activeCount);
            analysis.setNumRegistered(regCount);
            analysis.setNumRetention1d(numRetention1d);
            analysis.setCreated(new Date());
            analysis.setUpdated(new Date());
            analysis.setRecordDate(new SimpleDateFormat("yyyy-MM-dd").parse(today));
            analysisMapper.insert(analysis);
        }
    }
}
